//
//  HWStrategyViewController.swift
//  HWanGame
//
//  Created by Apple on 2024/8/12.
//  Copyright © 2024 94Wan. All rights reserved.
//
// 论坛
import UIKit
import JXPagingView
import ZLPhotoBrowser
import Stevia

private let headerID    = "HWStrategyHeaderView"

class HWStrategyViewController: HWBaseViewController {

    private let scrollView = UIScrollView()
    private let containerView = UIView()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(HWWuKongEquipCell.self, HWStrategyImageTextCell.self)
        tableView.register(HWHomeTitleHeaderView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.isScrollEnabled = false
        return tableView
    }()
    private lazy var collectionView: UICollectionView = {
        let flowL = UICollectionViewFlowLayout.init()
        flowL.minimumLineSpacing = 0
        flowL.minimumInteritemSpacing = 0
        flowL.scrollDirection = .vertical
        let collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: flowL)
        collectionView.delegate = collectionProtocol
        collectionView.dataSource = collectionProtocol
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.contentInsetAdjustmentBehavior = .never
        collectionView.register(HWGameCommunityListCell.self, forCellWithReuseIdentifier: "HWGameCommunityListCell")
        collectionView.register(HWGameCommunityListHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HWGameCommunityListHeader")
        collectionView.register(HWGameCommunityListFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "HWGameCommunityListFooter")
        collectionView.isScrollEnabled = false
        return collectionView
    }()
    private var collectionProtocol = HWGameCommunityListProtocol()
    var listViewDidScrollCallback: ((UIScrollView) -> ())?
    private var httpManager = HWHomeHttpManager()
    private var bolckData: [HWStrategyBlockModel]?
    private var sourceData: [HWGameCommunityListModel]?
    private var pageIndex = 1
    
    var shequID = "" {
        didSet{
            loadData()
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = "#E8E9EB".toColor
        view.subviews{
            scrollView.subviews{
                containerView.subviews{
                    tableView
                    collectionView
                }
            }
        }

        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }

        scrollView.backgroundColor = .clear
        containerView.backgroundColor = .clear
        scrollView.top(0).leading(0).width(.screenWidth).bottom(0)
        containerView.fillContainer().width(.screenWidth)
        tableView.top(0).leading(0).width(.screenWidth).height(500)
        collectionView.leading(0).width(.screenWidth).height(.screenHeight).bottom(0)
        collectionView.Top == tableView.Bottom
        
        collectionView.ly_emptyView = LYEmptyView.emptyActionView(withImageStr: "", titleStr: "", detailStr: "暂无数据", btnTitleStr: "点击刷新", btnClick: {
            self.loadData()
        })
        collectionView.ly_emptyView.actionBtnCornerRadius = 15*widthScale
        collectionView.ly_emptyView.actionBtnHeight = 30*widthScale
        collectionView.ly_emptyView.contentViewOffset = -120*widthScale
        
        addAction()
        addRefresh()
        NotificationCenter.default.addObserver(self, selector: #selector(pushToInfoDetailVC), name: .toInfoDetailVC, object: nil)
    }

    private func updateUI(){
        
        DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
            self.collectionView.heightConstraint?.constant = self.collectionProtocol.height - 15*widthScale
        }
    }
    
    @objc private func pushToInfoDetailVC(_ noti: Notification){
        
        if let infoID = noti.userInfo?["infoID"] as? Int {
            let detail = HWGameCommunityDetailController()
            detail.newsId = String(infoID)
            self.navigationController?.pushViewController(detail, animated: true)
        }
    }
}

//MARK: - loadData
extension HWStrategyViewController {

    private func loadData(){
        scrollView.mj_footer?.endRefreshing()
        self.collectionProtocol.height = 0
        httpManager.getStrategyInfo(shequId: shequID,p: pageIndex) { model in
            self.scrollView.mj_header?.endRefreshing()
            self.bolckData = model.blocks
            self.sourceData = model.data
            self.collectionProtocol.models = model.data
            if let blocks = model.blocks {
                var height = 0.0
                let count = blocks.count + 1
                height = Double(count) * 40.0*widthScale
                for md in blocks {
                    if md.image == 1 {
                        height += 175*widthScale
                    }else{
                        height += 65*widthScale
                    }
                }
                self.tableView.heightConstraint?.constant = height
            }else{
                self.tableView.heightConstraint?.constant = 0
            }
            self.updateUI()
            self.tableView.reloadData()
            self.collectionView.reloadData()
        } failure: { err in
            self.scrollView.mj_header?.endRefreshing()
            self.scrollView.mj_footer?.endRefreshing()
        }

    }
    
    private func addRefresh() {
        
        scrollView.mj_header = MJRefreshNormalHeader()
        scrollView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        scrollView.mj_footer = MJRefreshBackNormalFooter()
        scrollView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
    }
    
    @objc private func loadNewData() -> () {
        pageIndex = 1
        loadData()
    }
    
    @objc private func loadMoreData() -> () {
        pageIndex += 1
        
        httpManager.getStrategyInfo(shequId: shequID,p: pageIndex) { model in
            self.scrollView.mj_header?.endRefreshing()
            self.scrollView.mj_footer?.endRefreshing()
            if (model.data?.count ?? 0) > 0 {
                for mod in (model.data)! {
                    self.sourceData?.append(mod)
                }
                self.collectionProtocol.models = self.sourceData
                self.updateUI()
                self.collectionView.reloadData()
            } else {
                self.scrollView.mj_footer.endRefreshingWithNoMoreData()
            }
        } failure: { error in
            self.scrollView.mj_header?.endRefreshing()
            self.scrollView.mj_footer?.endRefreshing()
        }
        
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension HWStrategyViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        let count = (bolckData?.count ?? 0) + 1
        return count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if section == (bolckData?.count ?? 0) {
            return 0
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = bolckData?[indexPath.section]
        if model?.image == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "HWStrategyImageTextCell", for: indexPath) as! HWStrategyImageTextCell
            cell.news = model?.news
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "HWWuKongEquipCell", for: indexPath) as! HWWuKongEquipCell
            cell.news = model?.news
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let model = bolckData?[indexPath.section]
        if model?.image == 1 {
            return 175*widthScale
        }else{

            return 65*widthScale
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! HWHomeTitleHeaderView
        if section == (bolckData?.count ?? 0) {
            header.titleString = "用户动态"
        }else{
            let model = bolckData?[section]
            header.titleString = model?.name
        }
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 40*widthScale
    }
}

//MARK: collectionview action
extension HWStrategyViewController {
    func addAction() -> Void {
        collectionProtocol.scrollDidScroll = {
            scrollView in
            self.listViewDidScrollCallback?(scrollView)
        }
        
        collectionProtocol.didSelectImage = {
            index,images in
            var datas: [Any] = []
            for a in images {
                if a.count > 0 {
                    datas.append(URL(string: a)!)
                }
            }
            let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
                
                return .image
            } urlImageLoader: { (url, imageView, progress, loadFinish) in
                imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                    let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                    debugPrint("\(percentage)")
                    progress(percentage)
                } completionHandler: { (_) in
                    loadFinish()
                }
            }
            
            vc.doneBlock = { (datas) in
                debugPrint(datas)
            }
            
            vc.modalPresentationStyle = .fullScreen
            self.showDetailViewController(vc, sender: nil)
            
        }
        
        collectionProtocol.didSelectVideo = {
            url in
            
            let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
                
                return .video
            } urlImageLoader: { (url, imageView, progress, loadFinish) in
                imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                    let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                    debugPrint("\(percentage)")
                    progress(percentage)
                } completionHandler: { (_) in
                    loadFinish()
                }
            }
            
            vc.doneBlock = { (datas) in
                debugPrint(datas)
            }
            
            vc.modalPresentationStyle = .fullScreen
            self.showDetailViewController(vc, sender: nil)
        }
        
        collectionProtocol.jumpToDetail = {
            mod in
            let detail = HWGameCommunityDetailController()
            detail.newsId = mod.id
            self.navigationController?.pushViewController(detail, animated: true)
        }
        
//        collectionProtocol.zanButtonClick = {
//            mod in
//            self.httpManager.gameCommunityZan(pid: mod.id, puid: mod.uid, type: "0") { message in
//                self.loadData()
//            } failure: { errorString in
//                self.view.showHUD(title: errorString)
//            }
//
//        }
        
//        collectionProtocol.delButtonClick = {
//            mod in
//            let alert = UIAlertController(title: "删除文章", message: "是否确认删除？", preferredStyle: UIAlertController.Style.alert)
//            alert.addAction(UIAlertAction(title: "确认", style: .default, handler: { action in
//                self.httpManager.gameCommunityCommentDel(id: mod.id) { nessage in
//                    self.loadData()
//                } failure: { errorString in
//                    self.view.showHUD(title: errorString)
//                }
//            }))
//            alert.addAction(UIAlertAction(title: "取消", style: .default, handler: { action in
//                
//            }))
//            self.present(alert, animated: true)
//
//        }
    }
}

extension HWStrategyViewController:JXPagingViewListViewDelegate {
    func listView() -> UIView {
        return view
    }
    
    func listScrollView() -> UIScrollView {
        return self.tableView
    }
    
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }
    
}
